package com.ds.esd.formula.service;

import com.ds.bpm.formula.ParticipantSelect;
import com.ds.common.JDSException;
import com.ds.common.util.StringUtility;
import com.ds.config.*;
import com.ds.enums.db.MethodChinaName;
import com.ds.esb.config.formula.FormulaParams;
import com.ds.esd.bpm.BPMFactory;
import com.ds.esd.client.ESDFacrory;
import com.ds.esd.client.ProjectVersion;
import com.ds.esd.custom.annotation.DialogAnnotation;
import com.ds.esd.custom.annotation.GridViewAnnotation;
import com.ds.esd.custom.annotation.PopTreeViewAnnotation;
import com.ds.esd.custom.api.annotation.APIEventAnnotation;
import com.ds.esd.custom.api.enums.CustomCallBack;
import com.ds.esd.custom.enums.CustomMenuItem;
import com.ds.esd.custom.module.annotation.ModuleAnnotation;
import com.ds.esd.formula.component.PackagePopTree;
import com.ds.esd.formula.component.PackagesPopTree;
import com.ds.esd.formula.component.grid.PackageGridView;
import com.ds.esd.project.config.FormulaInst;
import com.ds.esd.project.config.FormulaInstParams;
import com.ds.esd.project.config.ProjectConfig;
import com.ds.esd.tool.module.EUModule;
import com.ds.esd.tool.module.EUPackage;
import com.ds.esd.util.TreePageUtil;
import com.ds.web.util.PageUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@RequestMapping(path = "/admin/formula/component/package/")
@MethodChinaName(cname = "Package包", imageClass = "spafont spa-icon-c-iconslist")

public class PackageFService {


    @GridViewAnnotation(addPath = "PackagesPopTree")
    @RequestMapping("Indexs")
    @ModuleAnnotation()
    @APIEventAnnotation(autoRun = true, bindMenu = CustomMenuItem.indexs)
    @ResponseBody
    public ListResultModel<List<PackageGridView>> getIndexs(String projectName, String currClassName, String formulaInstId, String parameterCode) {
        ListResultModel<List<PackageGridView>> model = new ListResultModel<>();
        try {
            Map<String, FormulaInst> instMap = new HashMap<>();
            if (currClassName != null && !currClassName.equals("")) {
                EUModule euModule = ESDFacrory.getESDClient().getModule(currClassName, projectName);
                instMap = euModule.getComponent().getFormulas();
            } else {
                ProjectConfig config = ESDFacrory.getESDClient().getProjectByName(projectName).getConfig();
                instMap = config.getFormulas();
            }

            FormulaInst inst = instMap.get(formulaInstId);
            List<FormulaInstParams> formulaParamList = new ArrayList<FormulaInstParams>();
            Collection<FormulaInstParams> formulaParams = inst.getParamsMap().values();
            for (FormulaInstParams param : formulaParams) {
                if (param.getParameterCode().equals(parameterCode)) {
                    param.getParameterValues().forEach((key, value) -> {
                        FormulaInstParams paramInst = new FormulaInstParams(param, key, value);
                        formulaParamList.add(paramInst);
                    });
                }
            }
            model = PageUtil.getDefaultPageList(formulaParamList, PackageGridView.class);
        } catch (JDSException e) {
            model = new ErrorListResultModel();
            ((ErrorListResultModel) model).setErrdes(e.getMessage());
        }

        return model;
    }


    @PopTreeViewAnnotation()
    @RequestMapping("PackagesPopTree")
    @ModuleAnnotation(dynLoad = true, caption = "添加菜单")
    @APIEventAnnotation(bindMenu = CustomMenuItem.add)
    @DialogAnnotation(width = "300", height = "450")
    @ResponseBody
    public TreeListResultModel<List<PackagesPopTree>> getPackagesPopTree(String formulaInstId, String parameterCode, String currClassName, String projectName) {
        TreeListResultModel<List<PackagesPopTree>> model = new TreeListResultModel<>();
        try {
            List<EUPackage> packages = ESDFacrory.getESDClient().getProjectByName(projectName).getActiveProjectVersion().getTopPackages();
            model = TreePageUtil.getTreeList(packages, PackagesPopTree.class);
        } catch (JDSException e) {
            e.printStackTrace();
            model = new ErrorListResultModel(e.getMessage());
        }
        return model;
    }


    @GridViewAnnotation(addPath = "PackagePopTree")
    @RequestMapping("Index")
    @ModuleAnnotation()
    @APIEventAnnotation(autoRun = true, bindMenu = CustomMenuItem.index)
    @ResponseBody
    public ListResultModel<List<PackageGridView>> getIndex(String projectName, String formulaInstId, String currClassName, String parameterCode) {
        ListResultModel<List<PackageGridView>> model = new ListResultModel<>();
        try {
            ProjectConfig config = ESDFacrory.getESDClient().getProjectByName(projectName).getConfig();

            Map<String, FormulaInst> instMap = new HashMap<>();

            if (currClassName != null && !currClassName.equals("")) {
                EUModule euModule = ESDFacrory.getESDClient().getModule(currClassName, projectName);
                instMap = euModule.getComponent().getFormulas();
            } else {
                config = ESDFacrory.getESDClient().getProjectByName(projectName).getConfig();
                instMap = config.getFormulas();
            }

            FormulaInst inst = instMap.get(formulaInstId);
            List<FormulaInstParams> formulaParamList = new ArrayList<FormulaInstParams>();
            Collection<FormulaInstParams> formulaParams = inst.getParamsMap().values();
            for (FormulaInstParams param : formulaParams) {
                if (param.getParameterCode().equals(parameterCode)) {
                    param.getParameterValues().forEach((key, value) -> {
                        FormulaInstParams paramInst = new FormulaInstParams(param, key, value);
                        formulaParamList.add(paramInst);
                    });
                }
            }
            model = PageUtil.getDefaultPageList(formulaParamList, PackageGridView.class);
        } catch (JDSException e) {
            model = new ErrorListResultModel();
            ((ErrorListResultModel) model).setErrdes(e.getMessage());
        }

        return model;
    }


    @PopTreeViewAnnotation()
    @RequestMapping("PackagePopTree")
    @ModuleAnnotation(dynLoad = true, caption = "添加菜单")
    @APIEventAnnotation(bindMenu = CustomMenuItem.add)
    @DialogAnnotation(width = "300", height = "450")
    @ResponseBody
    public TreeListResultModel<List<PackagePopTree>> getPackagePopTree(String formulaInstId, String parameterCode, String currClassName, String projectName) {
        TreeListResultModel<List<PackagePopTree>> model = new TreeListResultModel<>();
        try {
            List<EUPackage> packages = ESDFacrory.getESDClient().getProjectByName(projectName).getActiveProjectVersion().getTopPackages();
            model = TreePageUtil.getTreeList(packages, PackagePopTree.class);
        } catch (JDSException e) {
            e.printStackTrace();
            model = new ErrorListResultModel(e.getMessage());
        }
        return model;
    }

    @PopTreeViewAnnotation()
    @RequestMapping("loadChildPackage")
    @APIEventAnnotation(bindMenu = CustomMenuItem.loadChild)
    @ResponseBody
    public TreeListResultModel<List<PackagePopTree>> loadChildPackage(String projectName, String packageName, String currClassName, String formulaInstId, String parameterCode) {
        TreeListResultModel<List<PackagePopTree>> model = new TreeListResultModel<>();

        try {
            ProjectVersion version = ESDFacrory.getESDClient().getProjectVersionByName(projectName);
            EUPackage euPackage = version.getEUPackage(packageName);
            List<EUPackage> objs = new ArrayList<>();
            List<EUPackage> packages = euPackage.listChildren();
            for (EUPackage childPackage : packages) {
                objs.add(childPackage);
            }

            model = TreePageUtil.getTreeList(objs, PackagePopTree.class);
        } catch (JDSException e) {
            e.printStackTrace();
            model = new ErrorListResultModel(e.getMessage());
        }
        return model;
    }

    @RequestMapping("addPackage")
    @APIEventAnnotation(bindMenu = CustomMenuItem.treeSave, callback = {CustomCallBack.ReloadParent, CustomCallBack.Close})
    @ResponseBody
    public ResultModel<Boolean> addModule(String projectName, String PackagePopTree, String formulaInstId, String currClassName, String parameterCode, FormulaParams paramsType) {
        ResultModel<Boolean> model = new ResultModel<>();
        try {
            ProjectConfig config = ESDFacrory.getESDClient().getProjectByName(projectName).getConfig();
            EUModule euModule = null;
            Map<String, FormulaInst> instMap = new HashMap<>();

            if (currClassName != null && !currClassName.equals("")) {
                euModule = ESDFacrory.getESDClient().getModule(currClassName, projectName);
                instMap = euModule.getComponent().getFormulas();
            } else {
                instMap = config.getFormulas();
            }

            FormulaInst inst = instMap.get(formulaInstId);
            ParticipantSelect select = BPMFactory.getInstance(ESDFacrory.getESDClient().getSpace()).getFormulaById(inst.getParticipantSelectId());
            FormulaInstParams params = (FormulaInstParams) inst.getParamsMap().get(parameterCode);
            if (params == null) {
                params = new FormulaInstParams();
                params.setFormulaInstId(inst.getFormulaInstId());
                params.setParameterCode(parameterCode);
                params.setParameterName(parameterCode);
                if (paramsType != null && !paramsType.equals("")) {
                    params.setParamsType(paramsType);
                }
                inst.getParamsMap().put(parameterCode, params);
            }
            String[] paths = StringUtility.split(PackagePopTree, ";");

            for (String path : paths) {
                params.getParameterValues().put(path, path);
            }
            if (euModule != null) {
                euModule.update();
            } else {
                ESDFacrory.getESDClient().getProjectByName(projectName).updateConfig(config);
            }


        } catch (JDSException e) {
            model = new ErrorResultModel();
            ((ErrorResultModel<Boolean>) model).setErrdes(e.getMessage());
        }


        return model;
    }


    @RequestMapping("delPackage")
    @APIEventAnnotation(bindMenu = CustomMenuItem.delete, callback = {CustomCallBack.Reload})
    @ResponseBody
    public ResultModel<Boolean> delModule(String formulaInstId, String parameterCode, String currClassName, String projectName, String id) {
        ResultModel<Boolean> model = new ResultModel<>();
        try {
            EUModule euModule = null;
            ProjectConfig config = ESDFacrory.getESDClient().getProjectByName(projectName).getConfig();

            Map<String, FormulaInst> instMap = new HashMap<>();

            if (currClassName != null && !currClassName.equals("")) {
                euModule = ESDFacrory.getESDClient().getModule(currClassName, projectName);
                instMap = euModule.getComponent().getFormulas();
            } else {

                instMap = config.getFormulas();
            }

            FormulaInst inst = instMap.get(formulaInstId);
            FormulaInstParams params = (FormulaInstParams) inst.getParamsMap().get(parameterCode);
            String[] componentIds = StringUtility.split(id, ";");

            for (String path : componentIds) {
                params.getParameterValues().remove(path);
            }
            if (euModule != null) {
                euModule.update();
            } else {
                ESDFacrory.getESDClient().getProjectByName(projectName).updateConfig(config);
            }

        } catch (JDSException e) {
            model = new ErrorResultModel();
            ((ErrorResultModel<Boolean>) model).setErrdes(e.getMessage());
        }


        return model;
    }

    private FormulaInst getFormula(String projectId, String formulaInstId) throws JDSException {
        ProjectConfig config = ESDFacrory.getESDClient().getProjectById(projectId).getConfig();
        FormulaInst formulaInst = config.getFormulas().get(formulaInstId);
        return formulaInst;
    }

}


